import logging
from typing import Any

from aiogram import types
from aiogram_dialog import DialogManager
from fluentogram import TranslatorRunner

from src.application.order.service import OrderService
from src.application.user.service import UserService
from src.infrastructure.utils.helpers import get_expiring_on
from src.presentation.tg_bot.states import OrderDetailsSG

logger = logging.getLogger(__name__)


async def extend_order(call: types.CallbackQuery, _, manager: DialogManager):
    user_service: UserService = manager.middleware_data.get("user_service")
    order_service: OrderService = manager.middleware_data.get("order_service")
    locale: TranslatorRunner = manager.middleware_data.get("locale")

    order_id: int = manager.dialog_data.get("order_id")
    period: str = manager.dialog_data.get("period")
    extend_price: float = manager.dialog_data.get("extend_price")

    user = await user_service.get_user_by_tg_id(call.from_user.id)

    if user.balance < extend_price:
        await call.answer(locale.get("not-enough-balance", balance=user.balance))
        return

    order = await order_service.get_order_by_id(order_id)
    extended_expiring_on = await get_expiring_on(order.expiring_on, period)

    await order_service.update_order_expiring(order_id, extended_expiring_on)

    await call.answer(locale.get("order-extended-success"))
    await manager.switch_to(OrderDetailsSG.order_details)


async def set_proxy_period(_, widget: Any, manager: DialogManager):
    manager.dialog_data["period"] = widget.widget_id
    await manager.next()
